package com.scut.miaosha.rabbitmq;

import com.scut.miaosha.service.MiaoshaUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.scut.miaosha.domain.MiaoshaOrder;
import com.scut.miaosha.domain.MiaoshaUser;
import com.scut.miaosha.redis.RedisService;
import com.scut.miaosha.service.GoodsService;
import com.scut.miaosha.service.MiaoshaService;
import com.scut.miaosha.service.OrderService;
import com.scut.miaosha.vo.GoodsVo;

@Service
public class MQReceiver {

    	private static Logger log = LoggerFactory.getLogger(MQReceiver.class);

		@Autowired
		MiaoshaUserService miaoshaUserService;

		@Autowired
		RedisService redisService;

		@Autowired
		GoodsService goodsService;

		@Autowired
		OrderService orderService;

		@Autowired
		MiaoshaService miaoshaService;


        @RabbitListener(queues = MQConfig.MIAOSHA_QUEUE)
		public void receive(String message){
			log.info("receive message:"+message);
        	MiaoshaMessage mm = RedisService.stringToBean(message,MiaoshaMessage.class);
        	MiaoshaUser user = mm.getUser();
        	long goodsId = mm.getGoodsId();

        	//真实查数据库
        	GoodsVo goods = goodsService.getGoodsVoByGoodsId(goodsId);
            int stock = goods.getStockCount();
            if(stock <= 0)
			{
				return;
			}
			//判断是否已经秒杀到了
        	MiaoshaOrder order = orderService.getMiaoshaOrderByUserIdAndGoodsId(user.getId(),goodsId);
        	if(order != null)
        	{
				log.info(order.toString());
        		return ;
        	}
        	//生成秒杀订单
			miaoshaService.miaosha(user,goods);



		}

//		@RabbitListener(queues=MQConfig.QUEUE)
//		public void receive(String message) {
//			log.info("receive message:"+message);
//		}
//
//		@RabbitListener(queues=MQConfig.TOPIC_QUEUE1)
//		public void receiveTopic1(String message) {
//			log.info(" topic  queue1 message:"+message);
//		}
//
//		@RabbitListener(queues=MQConfig.TOPIC_QUEUE2)
//		public void receiveTopic2(String message) {
//			log.info(" topic  queue2 message:"+message);
//		}
//
//		@RabbitListener(queues=MQConfig.HEADER_QUEUE)
//		public void receiveHeaderQueue(byte[] message) {
//			log.info(" header  queue message:"+new String(message));
//		}


}
